using Microsoft.AspNetCore.Mvc;     // 因为ControllerBase等需要引入
using MyWebApi.Api.Entity;      // 因为Users表需要引入
using System.Collections.Generic;   // 因为泛型需要引入
using System.Linq;     // 因为Where 引入之后我们可以使用一种类似SQL的语法来查询任何形式的数据
using System;
using MyWebApi.Api.Repository;
using MyWebApi.Api.ParamModel;
using MyWebApi.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace MyWebApi.Api.Controllers
{
    // 特性
    // [Authorize]  // [Authorize]下的所有Api接口如：查询、删除、创建用户不能匿名访问，需要Token令牌才可访问
    [ApiController]
    [Route("[controller]")]

    public class OrderFormController : ControllerBase
    {

        // 实例化数据库
        // private MyWebApi.Api.Db.MyWebApiDb db = new Db.MyWebApiDb();

        // 定义为IRepository<T>的泛型接口未知数 T 为 users
        private IRepository<users> _usersRespository;   // 现在_usersRespository里包含IRepository<T>泛型接口里面的属性(可以使用这些属性来进行对Users表的操作)
        private IRepository<order_form> _order_form;

        private TokenParameter _tokenParameter;

        private readonly IConfiguration _configuration;


        // 一个构造函数：初始化UsersController控制器，使该控制器一开始就有以下的属性
        public OrderFormController(IConfiguration configuration,
         IRepository<users> usersRespository,
         IRepository<order_form> order_form

         )
        {
            _configuration = configuration;
            _tokenParameter = _configuration.GetSection("tokenParameter").Get<TokenParameter>();

            _usersRespository = usersRespository;
            _order_form = order_form;

        }


        // 添加订单
        [HttpPost]
        public dynamic addOrderForm(OrderFormModel model)
        {
            // 订单号(后端随机生成)
            var orderNumber = Guid.NewGuid().ToString("N");


            // 商品名称
            var commodityName = model.CommodityName;
            // 商品规格
            var norms = model.Norms;
            // 价格
            var money = model.Money;
            // 数量
            var quantity = model.Quantity;
            // 用户名
            var userName = model.UserName;
            // 收货地址
            var receivingSite = model.ReceivingSite;
            // 电话号码
            var CPN = model.CPN;
            // 支付方式
            var payment = model.Payment;
            // 订单状态(后端给，现在刚创建，状态为待收货)
            var orderFormStatus = "待收货";

            // 存入数据库
            var orderForm = new order_form
            {
                orderNumber = orderNumber,
                CommodityName = commodityName,
                Norms = norms,
                Money = money,
                UserName = userName,
                ReceivingSite = receivingSite,
                CPN = CPN,
                Payment = payment,
                OrderFormStatus = orderFormStatus,
                Quantity = quantity,
            };
            _order_form.Insert(orderForm);

            var res = new
            {
                Code = 1000,
                Data = orderForm,
                Msg = "添加订单成功"
            };
            return JsonHelper.Serialize(res);

        }

        // 根据用户名查询最新订单（支付完成后显示给用户看）
        [HttpGet, Route("user_sel_of")]
        public dynamic userSelOF(OrderFormModel model)
        {
            var userName = model.UserName;
            if (userName != null)
            {
                var userOf = _order_form.Table.Where(x => x.UserName == userName && x.IsDeleted == false).OrderByDescending(x => x.CreatedTime).ToList().FirstOrDefault();
                var res = new
                {
                    Code = 1000,
                    Data = userOf,
                    Msg = string.Format("查询{0}订单成功", userName)
                };
                return JsonHelper.Serialize(res);
            }
            else
            {
                var res = new
                {
                    Code = 1001,
                    Data = "用户不存在，查询订单失败",
                    Msg = "用户不存在，查询订单失败"
                };
                return JsonHelper.Serialize(res);
            }

        }

        // 查询全部订单（方便管理员管理）
        [HttpGet]
        public dynamic selOfderForm([FromQuery] Pager pater)
        {
            var pageIndex = pater.pageIndex;
            var pageSize = pater.pageSize;

            var allOfderForm = _order_form.Table.Where(x => x.IsDeleted == false).ToList();

            var u = allOfderForm.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); 

            var res = new
            {
                Code = 1000,
                Data = new { data = u, pager = new { pageIndex, pageSize, rowsTotal = allOfderForm.Count() } },
                Msg = "查询全部订单成功"
            };
            return JsonHelper.Serialize(res);
        }


        // 根据Id删除订单
        [HttpPost, Route("del_order_form/{ofderFormId}")]
        public dynamic delOrderForm(int ofderFormId)
        {
            var ofderForm = _order_form.GetById(ofderFormId);
            ofderForm.IsDeleted = true;
            _order_form.Update(ofderForm);

            var res = new
            {
                Code = 1000,
                Data = ofderForm,
                Msg = string.Format("删除ID为{0}的订单成功", ofderFormId)
            };
            return JsonHelper.Serialize(res);
        }







































    }
}